$(function () {
    var settings = {
        async: {
            dataType: 'json',
            dataFilter: function (treeId, treeNode, response) {
                if (response.success) {
                    var list = response.entity;
                    if(list!=null && list.length>0){
                        $.each(list,function (index,em) {
                            if(em.status==2){
                                em.helpName = em.helpName+'(隐藏)';
                                list[index] = em;
                            }
                        });
                    }
                    return list;
                } else {
                    icModale(0, response.message);
                }
            },
            enable: true,
            type: 'post',
            url: baseloaction + "/admin/manage/help/ajaxHelpCenter"
        },
        check: {
            enable: true
        },
        data: {
            key: {
                name: 'helpName',
                status: 'status'
            },
            simpleData: {
                enable: true,
                idKey: 'id',
                pIdKey: 'parentId',
                rootPId: null
            }
        },
        edit: {
            drag: {
                isMove: true
            },
            enable: true,
            removeTitle: function (treeId, treeNode) {
                return '删除：' + treeNode.helpName
            },
            renameTitle: function (treeId, treeNode) {
                return "修改：" + treeNode.helpName;
            },
            showRemoveBtn: function (treeId, treeNode) {
                return treeNode.helpType != 1;
            },
            showRenameBtn: true
        },
        view: {
            addHoverDom: function (treeId, treeNode) {
                var sObj = $("#" + treeNode.tId + "_span");
                if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0 || treeNode.level > 0 || treeNode.helpType == 1) return;
                var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加帮助文档' onfocus='this.blur();'></span>";
                sObj.after(addStr);
                var btn = $("#addBtn_" + treeNode.tId);
                if (btn) btn.bind("click", function () {
                    initUpdateOrAdd(0,treeNode.id,treeNode.status);
                    return false;
                });
            },
            removeHoverDom: function (treeId, treeNode) {//鼠标离开删除自定义按钮
                $("#addBtn_" + treeNode.tId).unbind().remove();
            },
            fontCss: function (treeId, treeNode) {
                if (typeof treeNode.highlight == 'undefined' || treeNode.highlight == false) {
                    if(treeNode.status==2){
                        return {color:"#dda525", "font-weight":"normal"};
                    }else{
                        return {color:"#333", "font-weight":"normal"};
                    }
                } else {
                    return {color:"#A60000", "font-weight":"bold"};
                }
            },
            showLine: true,
            selectedMulti: false
        },
        callback: {
            beforeDrop: function (treeId, treeNode, targetNode, moveType, isCopy) {
                if ('inner' != moveType && targetNode != null) {
                    targetNode = targetNode.getParentNode();
                }
                if ('inner' == moveType && targetNode.level > 0) {
                    icModale(0, '帮助文档只支持二级');
                    return false;
                }
                $.ajax({
                    url: baseloaction + '/admin/sys/help/ajax/updateHelpCenterParent',
                    data: {
                        'helpCenterId': treeNode[0].id,
                        'targetId': targetNode == null ? 0 : targetNode.id
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            icModale(0, response.message);
                            $.fn.zTree.getZTreeObj('helpCenter').moveNode(targetNode, treeNode[0], moveType, false);
                        } else {
                            icModale(0, response.message);
                        }
                    },
                    error: function () {
                        icModale(0, '系统错误，移动帮助文档节点失败');
                    }
                });
                return false;
            },
            beforeEditName: function (treeId, treeNode) {
                initUpdateOrAdd(treeNode.id,0,treeNode.status);
                return false;
            },
            beforeRemove: function (treeId, treeNode) {
                if (Array.isArray(treeNode) && treeNode.length > 0) {
                    var nodeIds = treeNode.map(function (node) {
                        return node.id;
                    }).join(',');
                    deleteHelpCenter(nodeIds);
                } else {
                    deleteHelpCenter(treeNode.id);
                }
                return false;
            },
            onAsyncError: function (event, treeId, treeNode, request, status) {
                icModale(0, "系统错误，帮助文档获取失败");
            },
            onAsyncSuccess: function (event, treeId, treeNode, msg) {
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                var list = treeObj.getNodes();
                treeObj.expandNode(list[0],true,true,true,true);
                var arr = treeObj.getNodes();
                if(arr && arr.length>0){
                    var node = arr[0];
                    treeObj.expandNode(node,true,true,true);
                }else{
                    setNotDataMsg()
                }
                initCount();
            }
        }
    };

    //如果没有数据这显示
    function setNotDataMsg() {
        $("#helpCenter").html('<p id="not-data-msg"><span class="c-4e fs16">亲，还没有创建帮助文档结构~~~</span></p>');
    }
    //初始化设置数据
    function initCount() {
        $('#function-count').html('共' + $('#helpCenter li').size() + '个帮助文档');
    }
    //获取数量
    function getCount() {
        return $('#helpCenter li').size();
    }

    //初始化权限树
    $.fn.zTree.init($('#helpCenter'), settings);

    $('body').on('click', '#showHelp', function () { //批量显示帮助文档
        var nodes = $.fn.zTree.getZTreeObj('helpCenter').getCheckedNodes(true);
        nodes = nodes.filter(function (node) {
            return node.status==2 && (node.check_Child_State ==-1 || node.check_Child_State == 2);
        });
        if (nodes.length == 0) {
            icModale(0, '没有隐藏或未选择选择任何的帮助文档菜单节点');
            return;
        }
        var nodeIds = nodes.map(function (node) {
            return node.id;
        }).join(',');
        updateHelpCenterStatus(nodeIds, 1);
    }).on('click', '#hiddenHelp', function () { //批量隐藏帮助文档
        var nodes = $.fn.zTree.getZTreeObj('helpCenter').getCheckedNodes(true);
        nodes = nodes.filter(function (node) {
            return node.status==1 && (node.check_Child_State ==-1 || node.check_Child_State == 2);
        });
        if (nodes.length == 0) {
            icModale(0, '没有显示或未选择选择任何的帮助文档菜单节点');
            return;
        }
        var nodeIds = nodes.map(function (node) {
            return node.id;
        }).join(',');
        updateHelpCenterStatus(nodeIds, 2);
    }).on('keyup', '#search-help', function () { //搜索权限树
        var keyword = this.value;
        var treeObj = $.fn.zTree.getZTreeObj("helpCenter");
        if ($.isEmptyObject($.trim(keyword))) {
            var nodes = treeObj.getNodesByFilter(function (node) {
                return node.highlight;
            }, false);
            if (nodes.length > 0) {
                nodes.forEach(function (node) {
                    node.highlight = false;
                    treeObj.updateNode(node);
                });
            }
            return;
        }
        treeObj.getNodesByFilter(function (node) {
            return node.highlight;
        }, false).forEach(function (node) {
            node.highlight = false;
            treeObj.updateNode(node);
        });
        treeObj.getNodesByFilter(function (node) {
            return node.helpName.indexOf(keyword) != -1;
        }).forEach(function (node) {
            node.highlight = true;
            treeObj.updateNode(node);
        });
    }).on('click', '#insertHelp', function () { //添加帮助文档
        initUpdateOrAdd(0,0,1);
    }).on('click',"#deleteHelp",function () {//批量删除
        var nodes = $.fn.zTree.getZTreeObj('helpCenter').getCheckedNodes(true);
        nodes = nodes.filter(function (node) {
            return node.check_Child_State ==-1 || node.check_Child_State == 2;
        });
        if (nodes.length == 0) {
            icModale(0, '请要删除的帮助菜单节点');
            return;
        }
        var nodeIds = nodes.map(function (node) {
            return node.id;
        }).join(',');
        deleteHelpCenter(nodeIds);
    });

    //全选权限树
    allSelete('all-function', function (status) {
        $.fn.zTree.getZTreeObj("helpCenter").checkAllNodes(status);
    });
    /**
     * 添加节点
     * @param id 帮助ID
     * @param parentId 父ID，没有父ID可以传0
     */
    function initUpdateOrAdd(id,parentId,status) {
        var url = baseloaction + '/admin/manage/help/initAdd?parentId='+parentId+"&status="+status;
        var title = "添加帮助文档";
        var status = true;
        if(id>0){
            title = "修改帮助文档";
            url = baseloaction + '/admin/manage/help/initUpdate?id='+id;
            status = false;
        }
        parent.layer.open({
            type: 2,
            title: '<strong>'+title+'</strong><small class="ml10"></small>',
            shadeClose: false,
            shade: [0.3, '#000000'],
            maxmin: true, //开启最大化最小化按钮
            btn:["保存帮助文档","取消"],
            area: winArea,
            content: url,
            yes: function(index, layero){
                var iframeName = layero.find("iframe").attr('name');
                var params = $(parent.window.frames[iframeName].document).find("form").serializeJSON();
                params = JSON.stringify(params);
                $.ajax({
                    url: baseloaction +'/admin/manage/help/saveHelpCenter',
                    contentType:'application/json;charset=utf-8',
                    type:'post',
                    dataType:'json',
                    data:params,
                    success:function (result) {
                        if(result.success==true){
                            var helpCenter = result.entity;
                            var treeObj = $.fn.zTree.getZTreeObj("helpCenter");
                            if(status==false){//修改节点
                                var nodeList = treeObj.getNodesByParam("id",helpCenter.id,null);
                                if(helpCenter.status==1){
                                    nodeList[0].helpName = helpCenter.helpName;
                                }else{
                                    nodeList[0].helpName = helpCenter.helpName+'(隐藏)';
                                }
                                nodeList[0].status = helpCenter.status;
                                treeObj.updateNode(nodeList[0]);
                            }else{//添加节点
                                var parentId = result.parentId;
                                var parentNode = null;
                                if(parentId!=null){
                                    var nodeList = treeObj.getNodesByParam("id",parentId,null);
                                    if(nodeList!=null && nodeList.length > 0){
                                        parentNode = nodeList[0];
                                    }
                                }
                                if(helpCenter.status==2){
                                    helpCenter.helpName = helpCenter.helpName+'(隐藏)';
                                }
                                var nodes = new Array();
                                nodes.push(helpCenter);
                                treeObj.addNodes(parentNode,nodes);
                                $("#not-data-msg").remove();
                            }
                            parent.layer.close(index);
                        }else{
                            icModale(0, result.message);
                        }
                    },
                    error:function (error) {
                        icModale(0, "系统错误，保存帮助文档数据失败");
                    }
                });
            }
        });
    }
    /**
     * 修改帮助菜单状态
     * @param helpCenterIds ID串
     * @param status 状态，1正常，2隐藏
     * @return {boolean}
     */
    function updateHelpCenterStatus(helpCenterIds, status) {
        var tips;
        if (status == 1) {
            tips = '确认显示选中的节点？';
        } else if (status == 2) {
            tips = '确认隐藏选中的节点？';
        }
        icModale(2, tips, 3, function () {
            $.ajax({
                url: baseloaction + '/admin/manage/help/updateHelpCenterStatus',
                type:'post',
                data: {'ids': helpCenterIds, 'status': status},
                dataType: 'json',
                success: function (response) {
                    icModale(0, response.message);
                    if (response.success) {
                        var zTree = $.fn.zTree.getZTreeObj('helpCenter');
                        (helpCenterIds + '').split(',').forEach(function (id) {
                            var node = zTree.getNodeByParam('id', id, null);
                            node.status = status;
                            if(status==2){//如果是隐藏
                                node.helpName = node.helpName+'(隐藏)';
                            }else{//如果是显示
                                node.helpName = node.helpName.replace(/\(隐藏\)/g,'');
                            }
                            zTree.updateNode(node);
                        });
                    }
                },
                error: function (error) {
                    icModale(0, "系统错误，帮助文档修改失败");
                }
            });
        });
        return true;
    }

    //删除系统权限
    function deleteHelpCenter(helpIds) {
        icModale(2, '确认删除选中的节点？', 3, function () {
            $.ajax({
                url: baseloaction + '/admin/manage/help/deleteHelpCenter',
                type:'post',
                data: {'ids': helpIds},
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        icModale(0, response.message);
                        var zTree = $.fn.zTree.getZTreeObj('helpCenter');
                        (helpIds + '').split(',').forEach(function (id) {
                            var node = zTree.getNodeByParam('id', id, null);
                            zTree.removeNode(node);
                        });
                    } else {
                        icModale(0, response.message);
                    }
                },
                error: function (error) {
                    icModale(0, "系统错误，帮助文档删除失败");
                }
            });
        });
        return true;
    }
});


